
<?php
include "../config/Config.php";
include "../Common/ValidateParam.php";
include "../enum/ResponseTypeEnum.php";
include "../exception/BusinessException.php";

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // 校验并提取参数
    $username = isset($_POST['username']) ? $_POST['username'] : null;
    $phone = isset($_POST['phone']) ? $_POST['phone'] : null;
    $gender = isset($_POST['gender']) ? $_POST['gender'] : null;

    // 参数校验
    $checkRes = checkInput($username, $phone, $gender);

    if ($checkRes) {
        $addTime = time();
        $exeRes = executeSQL($username, $phone, $gender,$addTime);
        if ($exeRes) {
            echo "<script>
            alert('注册成功')
            window.location.href = 'Index.php';
              </script>";
        } else {
            echo "<script>
            alert(" . json_encode('插入失败，请稍后重试' .' ') . ")
            window.location.href = 'Index.php';
          </script>";
        }
        exit; // 重要：确保代码不会继续执行跳转之后的内容
    } else {
        echo "<script>
        alert(" . json_encode('请检查参数是否正确填写' .' ') . ")
        window.location.href = 'Index.php';
      </script>";

    }
}


function checkInput($username, $phone, $gender): bool
{
    if (!checkGender($gender) ||
        !checkName($username) ||
        !checkPhone($phone)) {
      return false;
    }
    return true;
}


/**
 * 抽离出数据库操作逻辑
* @param $username
* @param $phone
* @param $gender
* @param $addTime
* @return bool
 */
function executeSQL($username, $phone, $gender,$addTime): bool
{
    try {

        // 使用 prepare 方法准备 SQL 语句
        $queryByPhone = "SELECT count(*) FROM user WHERE phone = ? AND del = 1 ";

        // 预处理语句
        $conn = getDatabaseConnection();
        $stmt = $conn->prepare($queryByPhone);

        // 使用 bind_param 方法绑定参数
        $stmt->bind_param("s", $phone);

        // 执行语句
        $stmt->execute();

        // 获取结果集
        $preCheckDupRes = $stmt->get_result();

        $count = 0;
        // 提取count属性
        while ($row = $preCheckDupRes->fetch_assoc()) {
            $count = $row['count'];
        }

        // 电话号重复
        if ($count > 0) {
            return false;
        }

        // 执行插入
        $insertQuery = "INSERT INTO user (username, phone, gender, add_time, del) VALUES (?, ?, ?, ?, 0)";
        $stmt = $conn->prepare($insertQuery);

        // 绑定参数
        $stmt->bind_param("ssii", $username, $phone, $gender, $addTime);

        // 执行插入语句
        return $stmt->execute() ?? false;
    } catch (Exception $e) {
        echo $e->getMessage();
        return false;
    }
}